using System;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Celeriq.Common;
using Widgetsphere.Autos.FacetedNavigation;
using Widgetsphere.Autos.Websitev2.Objects;

namespace Widgetsphere.Autos.Websitev2.UserControls
{
	public partial class ListingGridMap : System.Web.UI.UserControl
	{
		#region Class Members

		GeoCodeCollection geoCodeList = new GeoCodeCollection();

		#endregion

		#region Page Events

		protected void Page_Load(object sender, EventArgs e)
		{
			//Deallocate the Google Maps when done
			this.Page.ClientScript.RegisterStartupScript(typeof(string), "mapstartup", "<script type='text/javascript'><!--document.body.onunload = GUnload;--></script>");

			//Insert the Google include script
			var includeScript = new Literal();
			includeScript.Text = "<script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key="+ ConfigurationManager.AppSettings["GoogleMapKey"] +"' type='text/javascript'></script>";

			this.Page.Header.Controls.Add(includeScript);

		}

		#endregion

		#region Methods

		public void Populate(ListingResults results)
		{
			//Loop and load all geo-coded entries
			foreach (var item in results.RecordList)
			{
				this.PopulateRecord(item);
			}

			this.LoadMap(geoCodeList);

		}

		public void Populate(ListingItem item)
		{
			this.PopulateRecord(item);
			this.LoadMap(geoCodeList);
		}

		private void PopulateRecord(ListingItem item)
		{
			var city = item.City;
			var state = item.State;
			var zip = item.ZIP;
			var description = item.Description;
			var title = item.Year + " " + item.Make + " " + item.Model;
			var subtitle = item.Price.Value.ToString("$###,###,##0");
			var latitude = item.Location.Latitude.ToString();
			var longitude = item.Location.Longitude.ToString();
			decimal distance = 0;
			if (item.Location != null && item.Location.Distance != null)
				distance = (decimal)item.Location.Distance;

			GeoCode code = null;
			if (geoCodeList.Contains(decimal.Parse(latitude), decimal.Parse(longitude)))
			{
				code = geoCodeList[decimal.Parse(latitude), decimal.Parse(longitude)];
			}
			else
			{
				code = new GeoCode(decimal.Parse(latitude), decimal.Parse(longitude));
				geoCodeList.Add(code);
			}

			if ((code.Latitude != 0) && (code.Longitude != 0))
			{
				if (description != "")
				{
					var d = description.Replace("\r", "");
					d = d.Replace("\n", "<br />");
					code.Description = @"<div class=\'iwstyle\' style=\'text-align:left;width:350px;padding:3px;\'>" + d + "</div>";
				}

				var imageURL = "/images/nophoto.jpg";
				var newPic = "/images/stock/" + item.Make.FormatCarImageFile() + "_" + item.Model.FormatCarImageFile() + ".jpg";
				var realFile = Server.MapPath(newPic);
				if (System.IO.File.Exists(realFile))
					imageURL = newPic;

				//This is for a registered listing
				code.IsRegistered = true;

				var tableText =
					"<b>" + Server.HtmlEncode(subtitle) + "</b><br />" +
					//Server.HtmlEncode(address) + "<br />" +
					Server.HtmlEncode(city) + ", " +
					Server.HtmlEncode(state) + " " + Server.HtmlEncode(zip);

				//Add distance for registered users
				//tableText += "<br /><br />Distance: " + decimal.Parse(distance).ToString("###,##0.0") + " miles";

				code.Text = "<table width='350px'>";
				code.Text += "<tr>";
				code.Text += "<td colspan='2'><h2>" + Server.HtmlEncode(Server.HtmlEncode(title)) + "</h2></td>";
				code.Text += "</tr><tr>";
				code.Text += "<td style='padding-right:10px;'><img src='" + imageURL + "' /></td>";
				code.Text += "<td style='text-align:left;'>" + tableText + "</td>";
				code.Text += "</tr></table>";
			}
		}

		private void LoadMap(List<GeoCode> geoCodeList)
		{
			//Get the map center
			var center = GeoHelper.GetCenter(geoCodeList);

			//Build the scritp to show markers
			var sb = new StringBuilder();
			sb.AppendLine("<script type='text/javascript'>");
			sb.AppendLine("<!--");
			sb.AppendLine("function ShowMeTheMap() {");
			sb.AppendLine("var map = new GMap2(document.getElementById('map'));");
			sb.AppendLine("if (GBrowserIsCompatible())");
			sb.AppendLine("{");
			sb.AppendLine("  map.addControl(new GSmallMapControl());");
			sb.AppendLine("  map.addControl(new GMapTypeControl());");
			sb.AppendLine("}");

			if (center != null)
			{
				sb.AppendLine("map.setCenter(new GLatLng(" + center.Latitude + ", " + center.Longitude + "), 5);");
			}
			sb.AppendLine("var marker;");
			sb.AppendLine("var point;");

			foreach (var code in geoCodeList)
			{
				sb.AppendLine("point = new GLatLng(" + code.Latitude + ", " + code.Longitude + ");");
				string html = code.Text.Replace("'", @"\'");
				var description = "";
				description = code.Description;
				description = description.Replace("'", "&apos;");
				description = description.Replace(@"""", "&quot;");
				description = "<div align='left'>Put a description here for a tabbed display!<br /> Google maps is so easy to apply to a listing website.</div>";
				description = description.Replace("'", @"\'");

				sb.AppendLine("marker = createMarkerTabbed(point, null, " + code.EntryId + ",'" + html + "', '" + description + "');");
				//sb.AppendLine("marker = createMarker(point, createIcon(), " + code.EntryId + ",'" + html + "');");

				sb.AppendLine("map.addOverlay(marker);");
			}
			sb.AppendLine("}");
			sb.AppendLine("setTimeout(\"ShowMeTheMap()\", 1000)");

			//If there are no items then do not show map
			if (center == null)
			{
				sb.AppendLine("document.getElementById('map').style.display = 'none';");
			}

			sb.AppendLine("-->");
			sb.AppendLine("</script>");

			Page.ClientScript.RegisterStartupScript(typeof(string), "startup", sb.ToString());
		}

		private string FixPhoto(string fileName)
		{
			fileName = fileName.Replace(" ", "");
			fileName = fileName.Replace("-", "");
			return fileName;
		}

		#endregion

	}
}